from flask import Blueprint
from flask_restful import Api
from flask_restful.reqparse import RequestParser
from flask_restful import Resource, marshal_with, Api, marshal
from flask import request, Blueprint, session

from webapp.config import api_utils
from webapp.config.api_utils import oper_log, check_auth
from webapp.dto_mapper import plan_page_fields
from webapp.schema import PlanSchema
from webapp.service.teach_service import PlanService

plan_app = Blueprint('plan', __name__, url_prefix='/api/plan')
plan_api = Api(plan_app)

parser = RequestParser()
parser.add_argument('id', location='json', type=int, trim=True, required=True)
parser.add_argument('planname', location='json', type=str, trim=True, required=True)
parser.add_argument('teachtype', location='json', type=int, trim=True, required=True)
parser.add_argument('plancontent', location='json', type=str, trim=False, required=False)
parser.add_argument('timerange', location='json', type=int, trim=True, required=False)

@plan_api.resource('', '/')
class PlanApi(Resource):
    @oper_log('查询教学计划', request)
    @check_auth('plan:list', request)
    @marshal_with(plan_page_fields)
    def get(self):
        params = request.args.items(multi=True)
        params_dict = api_utils.build_params(params)
        return PlanService.query_all(**params_dict)

    @oper_log('新增教学计划', request)
    @check_auth('plan:add', request)
    def post(self):
        parser_post = parser.copy()
        parser_post.remove_argument('id')
        parser_post.parse_args()
        params = request.get_json()
        schema = PlanSchema()
        curr_plan = schema.load(params, unknown="exclude")
        data = session["user"]
        curr_plan.sub_count = 0
        curr_plan.create_by = data["username"]
        PlanService.create(curr_plan=curr_plan)

    @oper_log('删除计划', request)
    @check_auth('plan:del', request)
    def delete(self):
        ids = request.get_json()
        plan_set = set()
        for _id in ids:
            plan_set.add(PlanService.find_by_id(id=_id))
        PlanService.delete(plan_set=plan_set)

    @oper_log('修改计划', request)
    @check_auth('plan:edit', request)
    def put(self):
        parser_put = parser.copy()
        parser_put.parse_args()
        params = request.get_json()
        schema = PlanSchema()
        curr_plan = schema.load(params, unknown="exclude")
        data = session["user"]
        curr_plan.update_by = data["username"]
        PlanService.update(curr_plan=curr_plan)
        return None, 204